package com.xuetang.controller.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xuetang.common.ApiResponse;
import com.xuetang.entity.Article;
import com.xuetang.entity.ArticleCategory;
import com.xuetang.service.ArticleService;

/**
 * 文章后台管理控制器
 */
@RestController
@RequestMapping("/admin/articles")
public class ArticleAdminController {

    @Autowired
    private ArticleService articleService;

    /**
     * 获取文章列表
     */
    @GetMapping("/list")
    public ApiResponse getArticleList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String keyword) {

        Map<String, Object> result = articleService.getArticleList(page, size, category, keyword);

        Map<String, Object> data = new HashMap<>();
        data.put("list", result.get("list"));
        data.put("total", result.get("total"));
        data.put("page", page);
        data.put("pageSize", size);
        data.put("totalPages", Math.ceil((Integer) result.get("total") / (double) size));

        return ApiResponse.success(data);
    }

    /**
     * 获取文章详情
     */
    @GetMapping("/detail/{id}")
    public ApiResponse getArticleDetail(@PathVariable Long id) {
        Article article = articleService.getArticleById(id);
        if (article == null) {
            return ApiResponse.error(404, "文章不存在");
        }
        return ApiResponse.success(article);
    }

    /**
     * 创建文章
     */
    @PostMapping("/create")
    public ApiResponse createArticle(@RequestBody Map<String, Object> params) {
        Article article = new Article();
        article.setTitle((String) params.get("title"));
        article.setSummary((String) params.get("summary"));
        article.setContent((String) params.get("content"));
        article.setCoverImage((String) params.get("coverImage"));
        article.setAuthor((String) params.get("author"));
        article.setAuthorTitle((String) params.get("authorTitle"));
        article.setHospital((String) params.get("hospital"));
        article.setDepartment((String) params.get("department"));
        article.setCategory((String) params.get("category"));
        article.setIsRecommended((Boolean) params.get("isRecommended"));
        article.setIsPublished((Boolean) params.get("isPublished"));
        article.setPublishDate(new Date());

        @SuppressWarnings("unchecked")
        List<String> tags = (List<String>) params.get("tags");

        Article savedArticle = articleService.saveArticle(article, tags);
        return ApiResponse.success(savedArticle);
    }

    /**
     * 更新文章
     */
    @PutMapping("/update/{id}")
    public ApiResponse updateArticle(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        Article article = articleService.getArticleById(id);
        if (article == null) {
            return ApiResponse.error(404, "文章不存在");
        }

        article.setTitle((String) params.get("title"));
        article.setSummary((String) params.get("summary"));
        article.setContent((String) params.get("content"));
        article.setCoverImage((String) params.get("coverImage"));
        article.setAuthor((String) params.get("author"));
        article.setAuthorTitle((String) params.get("authorTitle"));
        article.setHospital((String) params.get("hospital"));
        article.setDepartment((String) params.get("department"));
        article.setCategory((String) params.get("category"));
        article.setIsRecommended((Boolean) params.get("isRecommended"));
        article.setIsPublished((Boolean) params.get("isPublished"));

        @SuppressWarnings("unchecked")
        List<String> tags = (List<String>) params.get("tags");

        Article updatedArticle = articleService.saveArticle(article, tags);
        return ApiResponse.success(updatedArticle);
    }

    /**
     * 删除文章
     */
    @DeleteMapping("/delete/{id}")
    public ApiResponse deleteArticle(@PathVariable Long id) {
        Article article = articleService.getArticleById(id);
        if (article == null) {
            return ApiResponse.error(404, "文章不存在");
        }

        boolean success = articleService.deleteArticle(id);
        return success ? ApiResponse.success() : ApiResponse.error("删除失败");
    }

    /**
     * 获取文章分类列表
     */
    @GetMapping("/categories")
    public ApiResponse getCategories() {
        List<ArticleCategory> categories = articleService.getCategories();
        return ApiResponse.success(categories);
    }

    /**
     * 创建文章分类
     */
    @PostMapping("/categories/create")
    public ApiResponse createCategory(@RequestBody ArticleCategory category) {
        ArticleCategory savedCategory = articleService.saveCategory(category);
        return ApiResponse.success(savedCategory);
    }

    /**
     * 更新文章分类
     */
    @PutMapping("/categories/update/{id}")
    public ApiResponse updateCategory(@PathVariable Long id, @RequestBody ArticleCategory category) {
        category.setId(id);
        ArticleCategory updatedCategory = articleService.saveCategory(category);
        return ApiResponse.success(updatedCategory);
    }

    /**
     * 删除文章分类
     */
    @DeleteMapping("/categories/delete/{id}")
    public ApiResponse deleteCategory(@PathVariable Long id) {
        boolean success = articleService.deleteCategory(id);
        return success ? ApiResponse.success() : ApiResponse.error("删除失败");
    }

    /**
     * 获取所有标签
     */
    @GetMapping("/tags")
    public ApiResponse getAllTags() {
        List<String> tags = articleService.getAllTags();
        return ApiResponse.success(tags);
    }
}